﻿using System;
using System.Linq;
using JetBrains.Annotations;



namespace Crocodile.AbstractLanguage.Tree
{

    public class Nest<P,C> : ObservingList<C>
        where P : AbstractNode
        where C : AbstractNode
    {
        [NotNull]
        private readonly P Parent;


        public Nest([NotNull] P parent)
        {
            Parent = parent;
        }


        protected override void OnItemAdded(C item)
        {
            item.Parent = Parent;
        }


        protected override void OnItemRemoved(C item)
        {
            item.Parent = null;
        }


        [CanBeNull]
        public T FirstOf<T>([NotNull] Predicate<T> predicate)
            where T : C
        {
            return 
                list
                .Select(z => z as T)
                .Where(x => x != null && predicate(x))
                .FirstOrDefault();
        }


    }

}
